import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import Swiper from 'swiper';
import { usePersistFn, useInterval } from 'ahooks';
import Image from '@/components/Image';
import DefaultLiveCoverImage from '@/assets/images/default_live_cover_image.jpg';
import { viewSizeFormat } from '@/common/format';

import styles from '../style/Banner.scss';

const Banner = ({ list }) => {
  const [swiperInstance, setSwiperInstance] = useState(null);
  const swiperRef = useRef();

  // 初始化swiper
  const initSwiper = usePersistFn(() => {
    if (swiperInstance) {
      swiperInstance.update();
      swiperInstance.slideTo(0);
    } else {
      const instance = new Swiper(swiperRef.current, {
        slidesPerView: 1,
        spaceBetween: viewSizeFormat(20),
        wrapperClass: styles.wrapper,
        slideClass: styles.item,
        loop: true,
      });
      setSwiperInstance(instance);
    }
  });

  // 销毁
  const destroySwiper = () => {
    if (!swiperInstance) return;

    swiperInstance.destroy();
    setSwiperInstance(null);
  };

  // 下一个
  const onNextHandle = () => {
    if (!swiperInstance) return;

    swiperInstance.slideNext();
  };

  useInterval(onNextHandle, swiperInstance ? 5000 : undefined);

  useLayoutEffect(() => {
    initSwiper();
  }, []);

  useEffect(() => () => destroySwiper(), []);

  return (
    <div className={styles.container} ref={swiperRef}>
      <div className={styles.wrapper}>
        {list.map((row, index) => {
          // link_type跳转类型(0:直播 1:比赛 2:外部url 3:不跳转)
          if ([0, 1].includes(row.linkType) && row.toRecordId) {
            return (
              <Link className={styles.item} to={`/live/room/${row.toRecordId}?userId=true`} key={index}>
                <Image className={styles.image} src={row.url} defaultImage={DefaultLiveCoverImage} />
              </Link>
            );
          }
          if (row.linkType === 2) {
            return (
              <a key={index} className={styles.item} href={row.linkUrl || '/download'} target="_blank" rel="noreferrer">
                <Image className={styles.image} src={row.url} defaultImage={DefaultLiveCoverImage} />
              </a>
            );
          }
          return <Image className={styles.item} src={row.url} defaultImage={DefaultLiveCoverImage} key={index} />;
        })}
      </div>
    </div>
  );
};

export default Banner;
